package cn.iocoder.an.module.business.service.reportviewnew;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.an.module.business.dal.dataobject.reportviewnew.ReportConfigDO;
import cn.iocoder.an.module.business.dal.mysql.reportconfig.ReportConfigMapper;
import cn.iocoder.an.module.business.dal.mysql.reportviewnew.ReportViewNewMapper;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.an.module.business.controller.admin.reportviewnew.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.reportviewnew.ReportViewNewDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;


import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 消息推送配置 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class ReportViewNewServiceImpl implements ReportViewNewService {

    @Resource
    private ReportViewNewMapper reportViewNewMapper;
    @Resource
    private ReportConfigMapper reportConfigMapper;

    @Autowired
    private AdminUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createReportViewNew(ReportViewNewSaveReqVO createReqVO) {
        // 插入
        ReportViewNewDO reportViewNew = BeanUtils.toBean(createReqVO, ReportViewNewDO.class);
        reportViewNewMapper.insert(reportViewNew);
        setName(createReqVO.getReportConfigs());
        // 插入子表
        createReportConfigList(reportViewNew.getId(), createReqVO.getReportConfigs());
        // 返回
        return reportViewNew.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReportViewNew(ReportViewNewSaveReqVO updateReqVO) {
        // 校验存在
        validateReportViewNewExists(updateReqVO.getId());
        // 更新
        ReportViewNewDO updateObj = BeanUtils.toBean(updateReqVO, ReportViewNewDO.class);
        reportViewNewMapper.updateById(updateObj);
        setName(updateReqVO.getReportConfigs());
        // 更新子表
        updateReportConfigList(updateReqVO.getId(), updateReqVO.getReportConfigs());
    }

    public void setName(List<ReportConfigDO> list){
        for (ReportConfigDO reportConfigDO : list) {

            List<Long> dutyUserId = reportConfigDO.getDutyUserId();
            List<AdminUserDO> userList = userService.getUserList(dutyUserId);
            String dutyUserName = userList.stream()
                    .map(AdminUserDO::getNickname)                    // 提取 nickname
                    .filter(nickname -> nickname != null && !nickname.trim().isEmpty()) // 过滤 null/空
                    .collect(Collectors.joining(","));               // 用逗号拼接
            reportConfigDO.setDutyUserName(dutyUserName);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteReportViewNew(Long id) {
        // 校验存在
        validateReportViewNewExists(id);
        // 删除
        reportViewNewMapper.deleteById(id);

        // 删除子表
        deleteReportConfigByReportId(id);
    }

    @Override
        @Transactional(rollbackFor = Exception.class)
    public void deleteReportViewNewListByIds(List<Long> ids) {
        // 删除
        reportViewNewMapper.deleteByIds(ids);
    
    // 删除子表
            deleteReportConfigByReportIds(ids);
    }


    private void validateReportViewNewExists(Long id) {
        if (reportViewNewMapper.selectById(id) == null) {
            throw exception(REPORT_VIEW_NEW_NOT_EXISTS);
        }
    }

    @Override
    public ReportViewNewDO getReportViewNew(Long id) {
        return reportViewNewMapper.selectById(id);
    }

    @Override
    public PageResult<ReportViewNewDO> getReportViewNewPage(ReportViewNewPageReqVO pageReqVO) {
        return reportViewNewMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（报表消息推送配置） ====================

    @Override
    public List<ReportConfigDO> getReportConfigListByReportId(Long reportId) {
        return reportConfigMapper.selectListByReportId(reportId);
    }

    private void createReportConfigList(Long reportId, List<ReportConfigDO> list) {
        list.forEach(o -> o.setReportId(reportId).clean());
        reportConfigMapper.insertBatch(list);
    }

    private void updateReportConfigList(Long reportId, List<ReportConfigDO> list) {
	    list.forEach(o -> o.setReportId(reportId).clean());
	    List<ReportConfigDO> oldList = reportConfigMapper.selectListByReportId(reportId);
	    List<List<ReportConfigDO>> diffList = diffList(oldList, list, (oldVal, newVal) -> {
            boolean same = ObjectUtil.equal(oldVal.getId(), newVal.getId());
            if (same) {
                newVal.setId(oldVal.getId()).clean(); // 解决更新情况下：updateTime 不更新
            }
            return same;
	    });





	    // 第二步，批量添加、修改、删除
	    if (CollUtil.isNotEmpty(diffList.get(0))) {
	        reportConfigMapper.insertBatch(diffList.get(0));
	    }
	    if (CollUtil.isNotEmpty(diffList.get(1))) {
	        reportConfigMapper.updateBatch(diffList.get(1));
	    }
	    if (CollUtil.isNotEmpty(diffList.get(2))) {
	        reportConfigMapper.deleteByIds(convertList(diffList.get(2), ReportConfigDO::getId));
	    }
    }

    private void deleteReportConfigByReportId(Long reportId) {
        reportConfigMapper.deleteByReportId(reportId);
    }

	private void deleteReportConfigByReportIds(List<Long> reportIds) {
        reportConfigMapper.deleteByReportIds(reportIds);
	}

}